/**
 * Copyright (c) 2009-2011, chunquedong(YangJiandong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 
 * History:
 *     2010-05-05  Jed Young  Creation
 */
package chunmap.example.edit;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

import chunmap.app.MapCtrl;
import chunmap.app.tools.create.AreaTool;
import chunmap.app.tools.create.LineTool;
import chunmap.app.tools.create.PointTool;
import chunmap.data.feature.Feature;
import chunmap.data.feature.FeatureSet;
import chunmap.data.feature.Shape;
import chunmap.data.feature.ShapeFeature;
import chunmap.data.feature.VisitFunc;
import chunmap.data.provider.LayerFactory;
import chunmap.example.BaseMap;
import chunmap.example.UiUtil;
import chunmap.model.elem.EnvelopeBuf;
import chunmap.model.geom.Geometry;
import chunmap.model.geom.WktParseException;
import chunmap.model.geom.WktReader;
import chunmap.util.Function;
import chunmap.view.layer.VectorLayer;

public class GeometryEditor extends BaseMap {
	public static void main(String[] args) {

		GeometryEditor me = new GeometryEditor();
		me.init();
	}

	@Override
	protected void addLayer(MapCtrl map) {}
	
	@Override
	protected void addButton(){
		super.addButton();
		
		final Function listener=new Function(){
					@Override
					public Object call(Object... args) {
						Geometry g=(Geometry)args[0];
						add2Layer(g);
						map.refreshMap();
						return null;
					}};
		
		UiUtil.addButton(frame,map,"创建点",new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				PointTool tool=new PointTool();
				tool.onCreateFinish.add(listener);
				map.setCurrentPlug(tool);
			}
		});
		
		UiUtil.addButton(frame,map,"创建线",new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				LineTool tool=new LineTool();
				tool.onCreateFinish.add(listener);
				map.setCurrentPlug(tool);
			}
		});
		
		UiUtil.addButton(frame,map,"创建面",new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				AreaTool tool=new AreaTool();
				tool.onCreateFinish.add(listener);
				map.setCurrentPlug(tool);
			}
		});
		
		final JTextArea text=new JTextArea(5,70);
		text.setLineWrap(true);

		
		UiUtil.addButton(frame,map,"添加",new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				Geometry g =null;
				try{
					g= wktReader.read(text.getText().trim());
				}catch(WktParseException exp){
					JOptionPane.showMessageDialog(null
							, "无效的文本", "error", JOptionPane.ERROR_MESSAGE);
					return;
				}
                add2Layer(g);
                map.refreshMap();
			}
		});
		
		UiUtil.addButton(frame,map,"删除",new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				final VectorLayer l = (VectorLayer) map.getLayerCollection().getSelectedLayer();

	            if (l == null)
	            {
	                return;
	            }

	            l.getFeatures().find(new VisitFunc(){
					@Override
					public boolean execute(Feature f) {
						if (f != null)
		                {
		                    boolean success=f.getFeatureClass().remove(f);
		                    l.getFeatures().remove(f);
		                    if (success)
		                    {
		                        map.refreshMap();
		                    }
		                    return false;
		                }
		                return true;
					}
	            });
			}
		});
		
		
		frame.add(text);
		
		tool.onSelectChange.add(new Function(){
			@SuppressWarnings("unchecked")
			@Override
			public Object call(Object... args) {
				List<Feature> fs=(List<Feature>)args[0];
				if(fs.size()==0){
					text.setText("");
				}else{
					Geometry g=((Shape)fs.get(0)).getGeometry();
					text.setText(g.toString());
				}
				return null;
			}});
	}
	private WktReader wktReader = new WktReader();
    private VectorLayer layer;
	
	public void add2Layer(Geometry g)
    {
        if (layer == null)
        {
            List<Geometry> geometrys = new ArrayList<Geometry>();
            geometrys.add(g);

            layer = (VectorLayer)LayerFactory.createGeometryLayer(geometrys);

            map.getLayerCollection().add(layer);
            map.fullView();
        }
        else
        {
        	ShapeFeature f = createFeature(g);
            layer.getFeatures().insert(f);
            f.setFeatureClass(layer.getFeatures());

            EnvelopeBuf eb = new EnvelopeBuf(layer.getEnvelop());
            eb.mergeEnvelop(g.getEnvelop());
            ((FeatureSet)layer.getFeatures()).setEnvelope(eb.toEnvelop());
            map.getLayerCollection().reComputeEnvelop();
        }
    }
    private ShapeFeature createFeature(Geometry g)
    {
    	ShapeFeature shp = new ShapeFeature();
        shp.setGeometry ( g);
        return shp;
    }
}